<template>
  <div class="exam-list">
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索考试名称、分类或关键词..."
          size="large"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-bar">
        <div class="filter-group">
          <label>分类：</label>
          <el-select v-model="selectedCategory" placeholder="选择分类" @change="handleFilter">
            <el-option label="全部分类" value="" />
            <el-option 
              v-for="category in categories" 
              :key="category.value"
              :label="category.label" 
              :value="category.value" 
            />
          </el-select>
        </div>
        
        <div class="filter-group">
          <label>难度：</label>
          <el-select v-model="selectedDifficulty" placeholder="选择难度" @change="handleFilter">
            <el-option label="全部难度" value="" />
            <el-option label="初级" value="初级" />
            <el-option label="中级" value="中级" />
            <el-option label="高级" value="高级" />
          </el-select>
        </div>
        
        <div class="filter-group">
          <label>状态：</label>
          <el-select v-model="selectedStatus" placeholder="选择状态" @change="handleFilter">
            <el-option label="全部状态" value="" />
            <el-option label="可参加" value="available" />
            <el-option label="已参加" value="taken" />
            <el-option label="已过期" value="expired" />
          </el-select>
        </div>
        
        <div class="filter-group">
          <label>排序：</label>
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
            <el-option label="最新发布" value="latest" />
            <el-option label="最受欢迎" value="popular" />
            <el-option label="难度等级" value="difficulty" />
            <el-option label="考试时长" value="duration" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 考试列表 -->
    <div class="exams-container">
      <div class="exams-header">
        <h2>{{ getCategoryTitle() }}</h2>
        <span class="exam-count">共 {{ filteredExams.length }} 场考试</span>
      </div>
      
      <div class="exams-grid">
        <div 
          v-for="exam in paginatedExams" 
          :key="exam.id"
          class="exam-card"
          :class="{ disabled: exam.status === 'expired' }"
        >
          <div class="exam-header">
            <div class="exam-category">{{ exam.category }}</div>
            <div class="exam-badges">
              <el-tag :type="getDifficultyType(exam.difficulty)" size="small">
                {{ exam.difficulty }}
              </el-tag>
              <el-tag v-if="exam.isNew" type="warning" size="small">新</el-tag>
              <el-tag v-if="exam.isHot" type="danger" size="small">热门</el-tag>
            </div>
          </div>
          
          <div class="exam-content">
            <h3 class="exam-title">{{ exam.title }}</h3>
            <p class="exam-desc">{{ exam.description }}</p>
            
            <div class="exam-meta">
              <div class="meta-row">
                <div class="meta-item">
                  <el-icon><Clock /></el-icon>
                  <span>{{ exam.duration }}分钟</span>
                </div>
                <div class="meta-item">
                  <el-icon><Document /></el-icon>
                  <span>{{ exam.questionCount }}题</span>
                </div>
                <div class="meta-item">
                  <el-icon><Trophy /></el-icon>
                  <span>及格{{ exam.passingScore }}分</span>
                </div>
              </div>
              
              <div class="meta-row">
                <div class="meta-item">
                  <el-icon><User /></el-icon>
                  <span>{{ exam.participants }}人参加</span>
                </div>
                <div class="meta-item">
                  <el-icon><Star /></el-icon>
                  <span>{{ exam.rating }}分</span>
                </div>
                <div class="meta-item">
                  <el-icon><Calendar /></el-icon>
                  <span>{{ formatDate(exam.deadline) }}</span>
                </div>
              </div>
            </div>
            
            <div class="exam-progress" v-if="exam.userProgress">
              <div class="progress-info">
                <span class="progress-label">最佳成绩</span>
                <span class="progress-score">{{ exam.userProgress.bestScore }}分</span>
              </div>
              <div class="attempt-count">
                已参加 {{ exam.userProgress.attempts }} 次
              </div>
            </div>
          </div>
          
          <div class="exam-footer">
            <div class="exam-status">
              <el-tag 
                :type="getStatusType(exam.status)" 
                size="small"
              >
                {{ getStatusText(exam.status) }}
              </el-tag>
            </div>
            
            <div class="exam-actions">
              <el-button 
                size="small" 
                @click="viewExamDetail(exam)"
              >
                查看详情
              </el-button>
              <el-button 
                type="primary" 
                size="small"
                :disabled="exam.status === 'expired'"
                @click="startExam(exam)"
              >
                {{ getActionText(exam) }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="filteredExams.length === 0" class="empty-state">
        <EmptyState
          image="/images/empty-exams.svg"
          title="暂无考试"
          description="当前筛选条件下没有找到相关考试"
        >
          <el-button @click="resetFilters">
            重置筛选
          </el-button>
        </EmptyState>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="filteredExams.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          :total="filteredExams.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Search, Clock, Document, Trophy, User, Star, Calendar
} from '@element-plus/icons-vue'
import EmptyState from '@/components/global/EmptyState.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectedDifficulty = ref('')
const selectedStatus = ref('')
const sortBy = ref('latest')
const currentPage = ref(1)
const pageSize = ref(12)

// 分类数据
const categories = ref([
  { label: '前端开发', value: '前端开发' },
  { label: '后端开发', value: '后端开发' },
  { label: '移动开发', value: '移动开发' },
  { label: '数据科学', value: '数据科学' },
  { label: '人工智能', value: '人工智能' },
  { label: '云计算', value: '云计算' },
  { label: '网络安全', value: '网络安全' },
  { label: '产品设计', value: '产品设计' }
])

// 考试数据
const exams = ref([
  {
    id: 1,
    title: 'JavaScript基础能力测试',
    description: '测试JavaScript基础语法、DOM操作、异步编程等核心知识点',
    category: '前端开发',
    difficulty: '初级',
    duration: 60,
    questionCount: 50,
    participants: 1250,
    rating: 4.8,
    passingScore: 60,
    deadline: new Date('2024-12-31'),
    status: 'available',
    isNew: false,
    isHot: true,
    userProgress: {
      bestScore: 85,
      attempts: 2
    }
  },
  {
    id: 2,
    title: 'Vue.js框架认证考试',
    description: 'Vue.js组件开发、状态管理、路由配置等高级特性考核',
    category: '前端开发',
    difficulty: '中级',
    duration: 90,
    questionCount: 40,
    participants: 890,
    rating: 4.7,
    passingScore: 70,
    deadline: new Date('2024-12-31'),
    status: 'available',
    isNew: true,
    isHot: true
  },
  {
    id: 3,
    title: 'Node.js后端开发测试',
    description: 'Express框架、数据库操作、API设计等后端开发技能评估',
    category: '后端开发',
    difficulty: '中级',
    duration: 120,
    questionCount: 60,
    participants: 650,
    rating: 4.6,
    passingScore: 65,
    deadline: new Date('2024-12-31'),
    status: 'available',
    isNew: false,
    isHot: false
  },
  {
    id: 4,
    title: 'React高级开发认证',
    description: 'React Hooks、性能优化、状态管理等高级开发技能认证',
    category: '前端开发',
    difficulty: '高级',
    duration: 150,
    questionCount: 45,
    participants: 420,
    rating: 4.9,
    passingScore: 75,
    deadline: new Date('2024-12-31'),
    status: 'available',
    isNew: true,
    isHot: false
  },
  {
    id: 5,
    title: 'Python数据分析基础',
    description: 'NumPy、Pandas、Matplotlib等数据分析库的使用',
    category: '数据科学',
    difficulty: '初级',
    duration: 90,
    questionCount: 35,
    participants: 780,
    rating: 4.5,
    passingScore: 60,
    deadline: new Date('2024-01-01'),
    status: 'expired',
    isNew: false,
    isHot: false
  }
])

// 计算属性
const filteredExams = computed(() => {
  let filtered = exams.value

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(exam => 
      exam.title.toLowerCase().includes(keyword) ||
      exam.description.toLowerCase().includes(keyword) ||
      exam.category.toLowerCase().includes(keyword)
    )
  }

  // 分类筛选
  if (selectedCategory.value) {
    filtered = filtered.filter(exam => exam.category === selectedCategory.value)
  }

  // 难度筛选
  if (selectedDifficulty.value) {
    filtered = filtered.filter(exam => exam.difficulty === selectedDifficulty.value)
  }

  // 状态筛选
  if (selectedStatus.value) {
    filtered = filtered.filter(exam => exam.status === selectedStatus.value)
  }

  // 排序
  switch (sortBy.value) {
    case 'popular':
      filtered.sort((a, b) => b.participants - a.participants)
      break
    case 'difficulty':
      const difficultyOrder = { '初级': 1, '中级': 2, '高级': 3 }
      filtered.sort((a, b) => difficultyOrder[a.difficulty] - difficultyOrder[b.difficulty])
      break
    case 'duration':
      filtered.sort((a, b) => a.duration - b.duration)
      break
    default: // latest
      filtered.sort((a, b) => b.id - a.id)
  }

  return filtered
})

const paginatedExams = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredExams.value.slice(start, end)
})

// 方法
const getCategoryTitle = () => {
  if (selectedCategory.value) {
    return selectedCategory.value
  }
  return '全部考试'
}

const getDifficultyType = (difficulty) => {
  const types = {
    '初级': 'success',
    '中级': 'warning',
    '高级': 'danger'
  }
  return types[difficulty] || 'info'
}

const getStatusType = (status) => {
  const types = {
    'available': 'success',
    'taken': 'info',
    'expired': 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    'available': '可参加',
    'taken': '已参加',
    'expired': '已过期'
  }
  return texts[status] || '未知'
}

const getActionText = (exam) => {
  if (exam.status === 'expired') return '已过期'
  if (exam.userProgress) return '重新考试'
  return '开始考试'
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleSort = () => {
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const resetFilters = () => {
  searchKeyword.value = ''
  selectedCategory.value = ''
  selectedDifficulty.value = ''
  selectedStatus.value = ''
  sortBy.value = 'latest'
  currentPage.value = 1
}

const viewExamDetail = (exam) => {
  router.push(`/exam/detail/${exam.id}`)
}

const startExam = (exam) => {
  if (exam.status === 'expired') {
    ElMessage.warning('考试已过期')
    return
  }
  
  ElMessage.success(`准备开始考试：${exam.title}`)
  router.push(`/exam/take/${exam.id}`)
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.exam-list {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  padding: 20px;
}

.search-filter-section {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 24px;
}

.search-bar {
  margin-bottom: 20px;
  
  .el-input {
    max-width: 600px;
  }
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
  
  label {
    font-size: 14px;
    color: var(--el-text-color-regular);
    white-space: nowrap;
  }
  
  .el-select {
    width: 140px;
  }
}

.exams-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.exams-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
  
  .exam-count {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.exams-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.exam-card {
  border: 1px solid var(--el-border-color-extra-light);
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  
  &:hover:not(.disabled) {
    transform: translateY(-2px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
    border-color: var(--el-color-primary);
  }
  
  &.disabled {
    opacity: 0.6;
    background: var(--el-fill-color-extra-light);
  }
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.exam-category {
  font-size: 12px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  padding: 4px 8px;
  border-radius: 4px;
}

.exam-badges {
  display: flex;
  gap: 6px;
}

.exam-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
  @include text-ellipsis(2);
}

.exam-desc {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 16px;
  @include text-ellipsis(2);
}

.exam-meta {
  margin-bottom: 16px;
  
  .meta-row {
    display: flex;
    gap: 16px;
    margin-bottom: 8px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  
  .el-icon {
    color: var(--el-color-primary);
  }
}

.exam-progress {
  background: var(--el-fill-color-extra-light);
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 16px;
  
  .progress-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
    
    .progress-label {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
    
    .progress-score {
      font-weight: 600;
      color: var(--el-color-primary);
    }
  }
  
  .attempt-count {
    font-size: 11px;
    color: var(--el-text-color-placeholder);
  }
}

.exam-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

@media (max-width: 768px) {
  .exams-grid {
    grid-template-columns: 1fr;
  }
  
  .exam-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
    
    .exam-actions {
      justify-content: center;
    }
  }
}
</style>
